<template>
  <div>
    <x-header :title="title"></x-header>
    <group label-width="4em" label-margin-right="1.5em" label-align="left" gutter="0">
      <x-input title="学生姓名" placeholder="请输入学生真实姓名" v-model="orderInfo.studentName" @on-change="toPinyin" required>
      </x-input>
      <x-input title="姓名拼音" placeholder="请输入学生姓名拼音" v-model="orderInfo.pinYin" required>
        <x-button slot="right" type="primary" mini @click.native="toPinyin">生成拼音</x-button>
      </x-input>
      <popup-picker title="证件类型" popup-title="证件类型" :data="idTypeList" v-model="idType" :columns="1" show-name value-text-align="left" @on-change="changeIdType">
      </popup-picker>
      <x-input title="证件号码" placeholder="请输入证件号码" v-model="orderInfo.idNo" ref="idNo" :min="numMix" :max="numMax" required :isType="beIdCardNum" @on-change="changeIdNo">
      </x-input>
      <popup-picker title="国籍" popup-title="请选择国籍" :data="countryList" v-model="countryId" :columns="1" show-name value-text-align="left">
      </popup-picker>
      <popup-picker title="民族" popup-title="请选择民族" :data="nationList" v-model="nationId" :columns="1" show-name value-text-align="left">
      </popup-picker>
      <datetime title="出生日期" v-model="birth" value-text-align="left" :start-date="startDate">
      </datetime>
      <popup-picker title="性别" popup-title="请选择性别" :data="sexList" v-model="sex" :columns="1" show-name value-text-align="left">
      </popup-picker>
      <x-input title="联系电话" placeholder="请输入联系电话" v-model="orderInfo.mobile" ref="mobile" :max="13" is-type="china-mobile" @on-change="changeMobile">
      </x-input>
      <popup-picker title="考试科目" placeholder="请选择考试科目" popup-title="请选择考试科目" :data="subjectList" v-model="subjectId" ref="subjectId" :columns="1" show-name value-text-align="left" @on-change="changeExam">
      </popup-picker>
      <popup-picker title="现在级别" popup-title="请选择现在级别" :data="levelList1" v-model="originalLeavelId" :columns="1" show-name value-text-align="left" @on-change="changeExam">
      </popup-picker>
      <cell-box>
        <span v-html="levelNotice" class="notice"></span>
      </cell-box>
      <popup-picker title="考试级别" popup-title="请选择报考级别" :data="levelList2" v-model="leavelId" :columns="1" show-name value-text-align="left">
      </popup-picker>
      <x-input title="考试日期" placeholder="考试日期" v-model="examDay" readonly>
      </x-input>
      <x-input title="考试地点" placeholder="考试地点" v-model="examAddress" readonly>
      </x-input>
      <cell-box>
        <div>
          <div class="img-div">
            <img class="img-demo" src="../assets/img/img_demo.jpg">
            <img class="img-demo" :src="imgSrc">
            <div class="btn-div">
              <vue-core-image-upload class="upload-btn" inputOfFile="file" :crop="false" @imageuploaded="imageuploaded" @imageuploading="imageuploading" @errorhandle="errorhandle" text="" :max-file-size="5242880" compress="50" :url="uploadUrl">
                <x-button type="primary" mini>选择照片</x-button>
              </vue-core-image-upload>
              <x-button type="primary" @click.native="showPreview" mini>查看效果</x-button>
            </div>
          </div>
          <div>
            <span v-html="imgNotice" class="notice"></span>
          </div>
        </div>
      </cell-box>
      <x-input title="指导老师" placeholder="请输入指导老师姓名" v-model="orderInfo.teacher" ref="teacher" required>
      </x-input>
    </group>
    <flexbox class="apply-button">
      <flexbox-item :span="1"></flexbox-item>
      <flexbox-item :span="10">
        <x-button type="primary" @click.native="apply" :disabled="isDisabled">报名</x-button>
      </flexbox-item>
      <flexbox-item :span="1"></flexbox-item>
    </flexbox>
    <div v-transfer-dom>
      <popup v-model="show" :height="popUpHeight + 'px'">
        <div class="preview-div">
          <img class="preview-back" src="../assets/img/img_certificate.jpg">
          <img class="preview-front" :style="{width:imgWidth +'px', height:imgHeight + 'px'}" :src="imgSrc">
        </div>
      </popup>
    </div>
  </div>
</template>
<script>
import { codefans_net_CC2PY } from "../assets/js/pinyin.js";
import VueCoreImageUpload from "vue-core-image-upload";
import {
  TransferDom,
  XHeader,
  Group,
  XInput,
  XButton,
  PopupPicker,
  Datetime,
  CellBox,
  Popup,
  Flexbox,
  FlexboxItem
} from "vux";
export default {
  directives: {
    TransferDom
  },
  components: {
    XHeader,
    Group,
    XInput,
    XButton,
    PopupPicker,
    Datetime,
    CellBox,
    Popup,
    Flexbox,
    FlexboxItem,
    VueCoreImageUpload
  },
  data() {
    return {
      title: "考级报名",
      idTypeList: [],
      numMix: 18,
      numMax: 18,
      beIdCardNum: function(value) {
        var pattern = new RegExp(
          /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/
        );
        var isValid = pattern.exec(value);
        return {
          valid: isValid,
          msg: "请输入正确的身份证号"
        };
      },
      countryList: [],
      nationList: [],
      startDate: "1900-01-01",
      birth: "2000-01-01",
      sexList: [],
      subjectList: [],
      levelList: [],
      levelList1: [],
      levelNotice: "",
      examDay: "",
      examAddress: "",
      imgSrc: require("../assets/img/img_placeholder.jpg"),
      uploadUrl: "/api/common/uploadImg",
      imgNotice: "",
      screenWidth: "",
      imgWidth: "",
      imgHeight: "",
      popUpHeight: "",
      show: false,
      idType: [],
      countryId: [],
      nationId: [],
      sex: [],
      subjectId: [],
      originalLeavelId: [],
      isIdNoValid: false,
      isMobileValid: false,
      orderInfo: {
        id: "",
        studentName: "",
        pinYin: "",
        idType: "",
        idNo: "",
        countryId: "",
        nationId: "",
        birthYear: "",
        birthMonth: "",
        birthDay: "",
        sex: "",
        mobile: "",
        subjectId: "",
        originalLeavelId: "",
        leavelId: "",
        partenerId: "",
        pictureId: "",
        teacher: "",
        openid: "",
        batchId: ""
      }
    };
  },
  created: function() {
    const vm = this;
    vm.uploadUrl = "http://" + window.location.host.concat(vm.uploadUrl);
    vm.getIdTypeList();
    vm.getSexList();
    vm.getLevelParameter();
    vm.getImgParameter();
    vm.getCountryList();
    vm.getNationList();
    vm.getLevelList();
    vm.getSubjectList();
    vm.getDtOrders();
    vm.screenWidth = document.body.clientWidth;
    vm.imgWidth = (vm.screenWidth / 800) * 130;
    vm.imgHeight = (vm.screenWidth / 800) * 160;
    vm.popUpHeight = (vm.screenWidth / 800) * 1133;
    vm.top = (vm.screenWidth / 800) * 1133 * 0.4;
  },
  computed: {
    levelList2: function() {
      return this.levelList.slice(
        parseInt(this.originalLeavelId[0]) + 1,
        parseInt(this.originalLeavelId[0]) + 2
      );
    },
    leavelId: {
      get: function() {
        return [String(parseInt(this.originalLeavelId[0]) + 1)];
      },
      set: function() {}
    },
    isDisabled: function() {
      return (
        !this.orderInfo.studentName ||
        !this.orderInfo.pinYin ||
        !this.subjectId[0] ||
        !this.isIdNoValid ||
        !this.isMobileValid ||
        !this.orderInfo.pictureId ||
        !this.orderInfo.teacher
      );
    }
  },
  methods: {
    aaa: function() {
      vm.$vux.alert.show({
        content: "2222"
      });
    },
    toPinyin: function() {
      const vm = this;
      vm.orderInfo.pinYin = codefans_net_CC2PY(vm.orderInfo.studentName);
    },
    changeIdType: function(value) {
      const vm = this;
      vm.$refs.idNo.reset();
      if (value == 1) {
        (vm.numMix = 9),
          (vm.numMax = 9),
          (vm.beIdCardNum = function(value) {
            var pattern = new RegExp(/^G\d{8}|E\d{8}|E[A-Z]\d{7}$/);
            var isValid = pattern.exec(value);
            return {
              valid: isValid,
              msg: "请输入正确的护照号"
            };
          });
      } else {
        (vm.numMix = 18),
          (vm.numMax = 18),
          (vm.beIdCardNum = function(value) {
            var pattern = new RegExp(
              /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/
            );
            var isValid = pattern.exec(value);
            return {
              valid: isValid,
              msg: "请输入正确的身份证号"
            };
          });
      }
    },
    getIdTypeList: function() {
      const vm = this;
      this.$api
        .getEnum2(5)
        .then(response => {
          vm.idTypeList = response;
          vm.idType = [response[0].value];
        })
        .catch(err => {
          console.log("证件类型出错了" + err);
        });
    },
    getSexList: function() {
      const vm = this;
      this.$api
        .getEnum2(4)
        .then(response => {
          vm.sexList = response;
          vm.sex = [response[0].value];
        })
        .catch(err => {
          console.log("性别列表出错了" + err);
        });
    },
    getLevelParameter: function() {
      const vm = this;
      this.$api
        .getParameter(7)
        .then(response => {
          vm.levelNotice = response.value;
        })
        .catch(err => {
          console.log("等级提示信息出错了" + err);
        });
    },
    getImgParameter: function() {
      const vm = this;
      this.$api
        .getParameter(8)
        .then(response => {
          vm.imgNotice = response.value;
        })
        .catch(err => {
          console.log("照片提示信息出错了" + err);
        });
    },
    getCountryList: function() {
      const vm = this;
      this.$api
        .getEnum(2)
        .then(response => {
          vm.countryList = response;
          vm.countryId = ["268"];
        })
        .catch(err => {
          console.log("国家列表出错了" + err);
        });
    },
    getNationList: function() {
      const vm = this;
      this.$api
        .getEnum(1)
        .then(response => {
          vm.nationList = response;
          vm.nationId = ["20"];
        })
        .catch(err => {
          console.log("名族列表出错了" + err);
        });
    },
    getLevelList: function() {
      const vm = this;
      this.$api
        .getLevel()
        .then(response => {
          vm.levelList = response;
          vm.levelList1 = vm.levelList.slice(0, vm.levelList.length - 1);
          vm.originalLeavelId = [response[0].value];
        })
        .catch(err => {
          console.log("等级列表出错了" + err);
        });
    },
    getSubjectList: function() {
      const vm = this;
      this.$api
        .getSubject()
        .then(response => {
          vm.subjectList = response;
        })
        .catch(err => {
          console.log("科目列表出错了" + err);
        });
    },
    // 查询是否存在未支付的报名
    getDtOrders: function() {
      const vm = this;
      let data = {
        openid: vm.$store.getters.userId,
        batchId: vm.$store.getters.batchId,
        partenerId: vm.$store.getters.partnerId
      };
      this.$api
        .getDtOrders(data)
        .then(response => {
          if (response) {
            vm.orderInfo = response;
            vm.idType = [String(vm.orderInfo.idType)];
            vm.countryId = [String(vm.orderInfo.countryId)];
            vm.nationId = [String(vm.orderInfo.nationId)];
            vm.birth =
              vm.orderInfo.birthYear +
              "-" +
              vm.orderInfo.birthMonth +
              "-" +
              vm.orderInfo.birthDay;
            vm.sex = [String(vm.orderInfo.sex)];
            vm.subjectId = [String(vm.orderInfo.subjectId)];
            vm.originalLeavelId = [String(vm.orderInfo.originalLeavelId)];
            vm.leavelId = [String(vm.orderInfo.leavelId)];
            vm.changeExam();
            vm.getImg();
          }
        })
        .catch(err => {
          console.log("报名信息出错了" + err);
        });
    },
    getImg: function() {
      const vm = this;
      this.$api
        .getDtPicture({ id: vm.orderInfo.pictureId })
        .then(response => {
          vm.imgSrc = response.fileName;
        })
        .catch(err => {
          console.log("获取照片出错" + err);
        });
    },
    changeExam: function() {
      const vm = this;
      let data = {
        batchId: vm.$store.getters.batchId,
        partnerId: vm.$store.getters.partnerId,
        subjectId: vm.subjectId[0],
        leavelId: vm.originalLeavelId[0]
      };
      this.$api
        .getOrderSetting(data)
        .then(response => {
          if (response) {
            vm.examDay = response.examDay;
            vm.examAddress = response.examAddress;
          }
        })
        .catch(err => {
          console.log("出错了" + err);
        });
    },
    changeIdNo: function() {
      const vm = this;
      vm.isIdNoValid = vm.$refs.idNo.valid;
    },
    changeMobile: function() {
      const vm = this;
      vm.isMobileValid = vm.$refs.mobile.valid;
    },
    apply: function() {
      const vm = this;
      if (!vm.examDay) {
        this.$vux.alert.show({
          content: "考试不存在！"
        });
        return;
      }
      vm.orderInfo.idType = vm.idType[0];
      vm.orderInfo.countryId = vm.countryId[0];
      vm.orderInfo.nationId = vm.nationId[0];
      vm.orderInfo.birthYear = vm.birth.substr(0, 4);
      vm.orderInfo.birthMonth = vm.birth.substr(5, 2);
      vm.orderInfo.birthDay = vm.birth.substr(8);
      vm.orderInfo.sex = vm.sex[0];
      vm.orderInfo.subjectId = vm.subjectId[0];
      vm.orderInfo.originalLeavelId = vm.originalLeavelId[0];
      vm.orderInfo.leavelId = vm.leavelId[0];
      vm.orderInfo.partenerId = vm.$store.getters.partnerId;
      vm.orderInfo.openid = vm.$store.getters.userId;
      vm.orderInfo.batchId = vm.$store.getters.batchId;
      this.$api
        .addOrder(vm.orderInfo)
        .then(response => {
          vm.$router.push({ name: "Pay", params: { id: response.id } });
        })
        .catch(err => {
          console.log("出错了" + err);
        });
    },
    imageuploaded: function(res) {
      const vm = this;
      vm.imgSrc = res.info.fileName;
      vm.orderInfo.pictureId = res.info.id;
      vm.$store.commit("SWITCH_IS_LOADING", false);
      console.log(111111111)
    },
    imageuploading: function() {
      const vm = this;
      vm.$store.commit("SWITCH_IS_LOADING", true);
    },
    errorhandle: function(res) {
      const vm = this;
      vm.$store.commit("SWITCH_IS_LOADING", false)
      if (res == "FILE IS TOO LARGER MAX FILE IS 5.00MB") {
        this.$vux.alert.show({
          content: "请勿上传大于5M的照片"
        });
      } else {
        this.$vux.alert.show({
          content: "照片上传失败，请稍后重试！"
        });
      }
    },
    showPreview: function() {
      const vm = this;
      vm.show = true;
    }
  }
};
</script>
<style lang="less">
.vux-cell-value {
  color: #000 !important;
}
.icon {
  display: inline-block;
  vertical-align: middle;
  text-align: center;
  width: 50%;
}
.img-div {
  width: 100%;
  display: inline-flex;
}
.img-demo {
  width: 105px;
  height: 135px;
  margin: 0px 5px 0px 5px;
}
.btn-div {
  display: block;
  margin-top: 10%;
  margin-left: 5px;
}
.upload-btn {
  padding-bottom: 20%;
}
.notice {
  display: block;
  font-size: 12px;
  color: Red;
}
.preview-div {
  width: 100%;
  position: relative;
}
.preview-back {
  width: 100%;
}
.preview-front {
  position: absolute;
  left: 18%;
  top: 39%;
}
.apply-button {
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>
